/*
* Copyright (c) 2024 -present FengJinjian ( 751965763@qq.com )

* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package edu.vital.energy.longevity.controller;

import edu.vital.energy.longevity.common.ApiResponse;
import edu.vital.energy.longevity.domain.dto.order.OrderCreateDTO;
import edu.vital.energy.longevity.domain.dto.order.OrderQueryDTO;
import edu.vital.energy.longevity.domain.dto.order.OrderUpdateDTO;
import edu.vital.energy.longevity.service.IOrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 控制器
 * 提供的CRUD、导入导出、状态管理等功能
 *
 * @version 1.0.1
 * @author Feng JinJian
 * @date 2025-03-19
 */
@Slf4j
@Tag(name = "", description = "相关接口")
@RestController
@RequestMapping("/api/product-orders/")
public class OrderController {

    @Autowired
    private IOrderService orderService;

    @Operation(summary = "分页查询列表", description = "支持按编号、名称、状态等条件筛选", security = { @SecurityRequirement(name = "Authorization") })
    @GetMapping
    @Parameters({
            @Parameter(name = "satoken", in = ParameterIn.HEADER, required = true, description = "认证token"),
    })
    public ResponseEntity<?> page(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "查询条件") OrderQueryDTO query) {
        log.info("分页查询列表: pageNum={}, pageSize={}, query={}", pageNum, pageSize, query);
        try {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 0);
            result.put("data", orderService.getOrderPage(pageNum, pageSize, query));
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return handleError(e);
        }
    }

    @Operation(summary = "获取详情", description = "根据ID查询详细信息")
    @GetMapping("/{id}")
    public ResponseEntity<?> getById(
            @Parameter(description = "ID") @PathVariable Long id) {
        log.info("查询详情: id={}", id);
        try {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 0);
            result.put("data", orderService.getOrderById(id));
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return handleError(e);
        }
    }

    @Operation(summary = "新增", description = "创建新的记录")
    @PostMapping()
    public ResponseEntity<ApiResponse<ApiResponse>> create(
            @Parameter(description = "信息") @RequestBody @Valid OrderCreateDTO dto) {
        log.info("创建: {}", dto);
        try {
            Long id = orderService.createOrder(dto);
            return ResponseEntity.ok(new ApiResponse<ApiResponse>(0,"SUCCESS", "创建成功", ApiResponse.success(id)));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(new ApiResponse<>(1,"ERROR", e.getMessage(), null));
        }
    }

    @Operation(summary = "修改", description = "更新已有信息")
    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<Integer>> update(
            @Parameter(description = "ID") @PathVariable Long id,
            @Parameter(description = "更新信息") @RequestBody @Valid OrderUpdateDTO dto) {
        log.info("修改: id={}, dto={}", id, dto);
        try {
            int rows = orderService.updateOrder(id, dto);
            return ResponseEntity.ok(new ApiResponse<>(0,"SUCCESS","更新成功", rows));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(new ApiResponse<>(1,"ERROR", e.getMessage(), null));
        }
    }

    @Operation(summary = "删除", description = "根据ID删除")
    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Integer>> delete(
            @Parameter(description = "ID") @PathVariable Long id) {
        log.info("删除: id={}", id);
        try {
            int rows = orderService.deleteOrder(id);
            return ResponseEntity.ok(new ApiResponse<>(0,"SUCCESS", "删除成功", rows));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(new ApiResponse<>(1,"ERROR", e.getMessage(), null));
        }
    }

    @Operation(summary = "批量删除", description = "根据ID列表批量删除")
    @DeleteMapping("/batch")
    public ResponseEntity<ApiResponse<Integer>> batchDelete(
            @Parameter(description = "ID列表") @RequestBody List<Long> ids) {
        log.info("批量删除: ids={}", ids);
        try {
            int rows = orderService.batchDeleteOrder(ids);
            return ResponseEntity.ok(new ApiResponse<>(0,"SUCCESS", "批量删除成功", rows));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(new ApiResponse<>(1,"ERROR", e.getMessage(), null));
        }
    }

    @Operation(summary = "导出", description = "根据查询条件导出数据")
    @GetMapping("/export")
    public ResponseEntity<?> export(
            @Parameter(description = "查询条件") OrderQueryDTO query) {
        log.info("导出数据: query={}", query);
        try {
            byte[] data =null;
            return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=orders.xlsx")
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(data);
        } catch (Exception e) {
            return handleError(e);
        }
    }

    @Operation(summary = "导入", description = "从Excel文件导入数据")
    @PostMapping("/import")
    public ResponseEntity<?> importData(
            @Parameter(description = "Excel文件") @RequestParam("file") MultipartFile file) {
        log.info("导入数据: fileName={}", file.getOriginalFilename());
        try {

            return ResponseEntity.ok(Map.of("code", 0, "data", null));
        } catch (Exception e) {
            return handleError(e);
        }
    }

    @Operation(summary = "更新状态", description = "变更状态（如：草稿、审核中、已生效等）")
    @PutMapping("/{id}/status")
    public ResponseEntity<?> updateStatus(
            @Parameter(description = "ID") @PathVariable Long id,
            @Parameter(description = "状态值") @RequestParam Integer status) {
        log.info("更新状态: id={}, status={}", id, status);
        try {
            orderService.updateOrderStatus(id, status);
            return ResponseEntity.ok(Map.of("code", 0, "data", null));
        } catch (Exception e) {
            return handleError(e);
        }
    }

    private <T> ResponseEntity<ApiResponse<T>> handleError(Exception e) {
        log.error("操作异常", e);
        return ResponseEntity.badRequest().body(new ApiResponse<>(1,"ERROR", e.getMessage(), null));
    }
}
